<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <!--    <el-form ref="searchForm" :model="formData" size="small" :inline="true" label-width="68px">-->
    <!--      <el-form-item v-for="item in headerData" :key="item.headerKey" :prop="item.headerKey" :label="item.name" v-if="item.headerKey !== 'description'">-->
    <!--        <el-input v-model="formData[item.headerKey]" :placeholder="'请输入' + item.name" style="width: 150px" @input="handleNameInput" />-->
    <!--      </el-form-item>-->

    <!--      <el-form-item v-if="headerData.length > 0">-->
    <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchPage">搜索</el-button>-->
    <!--        <el-button type="warning" icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="checkPermission(['admin','user'])" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <!-- 添加数据对话框表单 -->
    <el-dialog ref="form" :title="title" :visible.sync="dialogVisible" width="25%" @close="cancel">
      <el-form ref="form" :model="data" label-width="80px" size="mini" :rules="rules">
        <el-form-item v-for="item in headerData" :key="item.headerKey" :prop="item.headerKey" :label="item.name">
          <!-- 判断是否是 startTime 或 endTime -->
          <div v-if="item.headerKey === 'startDate' || item.headerKey === 'endDate'" class="block">
            <el-date-picker
              :id="item.headerKey"
              v-model="data[item.headerKey]"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
            />
          </div>
          <!-- 普通输入框 -->
          <el-input
            v-else-if="item.headerKey !== 'description' && item.headerKey !== 'createTime'"
            :id="item.headerKey"
            v-model="data[item.headerKey]"
            :placeholder="'请输入' + item.name"
            style="width: 220px"
          />
          <!-- 文本区域输入框 -->
          <el-input
            v-else-if="item.headerKey !== 'createTime'"
            :id="item.headerKey"
            v-model="data[item.headerKey]"
            type="textarea"
            :placeholder="'请输入' + item.name"
            style="width: 220px"
            :rows="5"
          />

        </el-form-item>

        <el-form-item style="margin-left: 15%">
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="centerbutton" /> -->
      <el-table-column
        v-for="item in headerData"
        :key="item.headerKey"
        :prop="item.headerKey"
        :label="item.name"
        align="center"
        show-overflow-tooltip
        :width="(checkPermission(['admin','user'])&&(item.headerKey === 'description' ? 290 : 210)? 230 : 290)"
      />

      <el-table-column v-if="checkPermission(['admin','user'])" label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlechange(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteById(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, add, del, selectById, update } from '@/api/user_work.js'
import { query_docu } from '@/api/files.js'
import { query as filterQuery } from '@/api/docu_filter.js'
import checkPermission from '@/utils/permission'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      rules: {
        startDate: [
          { required: true, message: '开始日期不能为空', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '结束日期不能为空', trigger: 'change' }
        ],
        certifier: [
          { required: true, message: '证明人不能为空', trigger: 'blur' }
        ],
        sideline: [
          { required: true, message: '兼职不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' },
          { min: 10, message: '描述至少需要10个字符', trigger: 'blur' }
        ]
      },

      checkPermission,
      // 非单个禁用
      single: true,
      // 遮罩层
      loading: true,
      buttonState: '', // 存储按钮的状态
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      fileList: [],
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload'
      },
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      title: '',
      dialogVisible: false,
      sort: undefined,
      docu: {
        appendix: '0'
      },
      tableHeader: {
        name: '',
        sort: undefined
      },
      queryParams: {
        status: '',
        createTime: '', // 添加开始时间字段
        endTime: '' // 添加结束时间字段
      },
      entryDate: [], // 用于v-model绑定日期选择器的值
      value: {},
      schoolyear: {},
      createTime: '',
      endTime: '',
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      formData: {
        certifier: '',
        startDate: undefined,
        endDate: undefined,
        sideline: '',
        description: ''
      },
      headerData: [
        { name: '证明人', headerKey: 'certifier' },
        { name: '开始日期', headerKey: 'startDate' },
        { name: '结束日期', headerKey: 'endDate' },
        // { name: '创建时间', headerKey: 'createTime' },
        { name: '兼职经历', headerKey: 'sideline' },
        { name: '在何地、何单位工作学习及岗位情况', headerKey: 'description' }
      ],
      tableKey: 0,
      list: null,
      total: 0,
      zlId: '',
      data: {
        startDate: '',
        endDate: '',
        certifier: '',
        sideline: '',
        description: '',
        createTime: '' // 如果需要
      },
      fileName: '',
      fileUrl: '',
      docuFilterList: [],
      isAdd: true
    }
  },
  computed: {
    ...mapState(['name']),
    // 控制按钮是否禁用
    isFormDisabled() {
      // 当状态为启用（0）时，表单整体禁用
      return this.schoolyear.status === '0'
    },
    isTermDisabled() {
      // 单独控制学期学年项，状态为启用（0）时禁用
      return this.schoolyear.status === '0'
    }
  },

  mounted() {
    this.zlId = this.$route.params.id
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    queryDocuFilter() {
      filterQuery(this.zlId).then((res) => {
        this.docuFilterList = res.data
      })
    },
    cancel() {
      this.dialogVisible = false
      this.fileList = []
    },
    queryDocu() {
      query_docu(this.zlId).then((res) => {
        this.docu = res.data
      })
    },
    handleExport() {
      this.$confirm('是否导出所有数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 压缩包下载路径
          const downloadUrl =
            process.env.VUE_APP_BASE_API + '/data/export/' + this.zlId
          const fileName = `${this.docu.name + '-' + new Date().getTime()}.zip`

          // 调用下载方法
          this.download(downloadUrl, { method: 'POST' }, fileName)
        })
        .catch(() => {
          this.$message.info('已取消导出')
        })
    },
    uploadChange(file, fileList) {
      console.log(file.name, fileList)
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleExceed(files, fileList) {
      this.$message.error('上传文件超出限制')
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.fileName = response.data.fileName
      this.fileUrl = response.data.fileUrl
      this.$message({ message: '上传成功', type: 'success' })
    },
    searchPage() {
      this.page()
    },
    handleSortInput() {
      // 根据表头序号查找对应的表头名称
      const header = this.tableHeader.find(
        (header) => header.sort === this.sort
      )
      if (header) {
        this.name = header.name
      } else {
        this.name = undefined
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 表单重置
    reset() {
      this.dataId = ''
      for (var item of this.headerData) {
        this.$set(this.data, item.headerKey, '')
      }
    },
    handlechange(row) {
      this.reset()
      this.isAdd = false
      this.dialogVisible = true
      this.title = '修改数据'
      this.dataId = row.id
      console.log('id:', row.id)

      selectById(this.dataId).then((res) => {
        // 保留某些字段的重置状态
        const newData = { ...res.data }
        for (var item of this.headerData) {
          if (newData[item.headerKey] === undefined) {
            newData[item.headerKey] = ''
          }
        }
        this.data = newData

        // 调用 page 方法
        this.page()
      }).catch((error) => {
        console.error('Error fetching data by ID:', error)
      })
    },

    /** 导出按钮操作 */
    handleDelete(row) {
      // const userIds = row.userId || this.ids
      // this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
      //   return delUser(userIds)
      // }).then(() => {
      //   this.getList()
      //   this.$modal.msgSuccess('删除成功')
      // }).catch(() => { })
    },
    page() {
      this.loading = true
      const requestData = {
        pageNum: this.current,
        userId: this.zlId,
        pageSize: this.pageSize,
        startDate: this.formData.startDate,
        endDate: this.formData.endDate,
        certifier: this.formData.certifier,
        sideline: this.formData.sideline,
        description: this.formData.description

      }
      this.tableData = []

      page(requestData)
        .then((res) => {
          this.totalCount = res.data.total
          const dataList = res.data.records
          console.log('dataList:', dataList)
          this.tableData = []

          for (const item of dataList) {
            const data = item
            // 将 item 中的其他属性合并到 data 中
            data.id = item.id
            data.certifier = item.certifier
            data.description = item.description
            data.endDate = item.endDate
            data.startDate = item.startDate
            data.sideline = item.sideline

            // 将解析后的 data 对象推入 tableData
            this.tableData.push(data)
          }

          this.loading = false
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },

    handleAdd() {
      this.reset()
      this.dialogVisible = true
      this.title = '新增数据'
      this.isAdd = true
    },
    handleDateChange(val) {
      if (val) {
        this.queryParams.createTime = val[0] // 开始时间
        this.queryParams.endTime = val[1] // 结束时间
      } else {
        this.queryParams.createTime = ''
        this.queryParams.endTime = ''
      }
    },

    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },
    // 重置方法
    clear() {
      this.formData = {
        certifier: '',
        startDate: undefined,
        endDate: undefined,
        sideline: '',
        description: ''
      }
      this.page()
    },
    // 日期格式化
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0') // Months are zero-based
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
    },
    submit() {
      let operator
      console.log('this.data:', this.data)
      const requestData = {
        id: this.dataId,
        userId: this.zlId,
        certifier: this.data.certifier,
        startDate: this.formatDate(new Date(this.data.startDate)),
        endDate: this.formatDate(new Date(this.data.endDate)),
        sideline: this.data.sideline,
        description: this.data.description
      }
      console.log('startDate:')
      console.log('endDate:')
      console.log('requestData:', requestData)
      // 如果需要将空值设置为默认值，可以这样做
      Object.keys(requestData).forEach(key => {
        if (requestData[key] === null || requestData[key] === undefined || requestData[key] === '') {
          requestData[key] = null // 或者设置为其他默认值
        }
      })
      if (this.isAdd === false) {
        // 修改
        operator = update(requestData)
      } else if (this.isAdd === true) {
        operator = add(requestData)
        console.log('operator:', operator)
      }

      operator.then((resp) => {
        if (resp.code == '1') {
          this.$message({ message: '保存成功', type: 'success' })
          this.page()
        } else {
          this.$message.error(resp.msg)
        }
        this.dialogVisible = false
        // this.fileList = []
      })
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    deleteById(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定按钮
        const requestData = {
          id: row.id
        }

        // 发送 AJAX 请求
        del(requestData).then((resp) => {
          if (resp.code == 1) {
            // 删除成功
            this.$message.success('删除成功')
            this.loading = true
            this.page() // 调用 page 方法更新数据
          } else {
            this.$message.error(resp.msg)
          }
        }).catch((error) => {
          // 处理 AJAX 请求失败的情况
          this.$message.error('删除失败: ' + error.message)
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    ...mapMutations('schoolmanage', ['getname']),
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>
/* 全局CSS 或者在<style scoped>内 */
.el-form-item .is-disabled .el-input__inner,
.is-disabled .el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
.el-form-item .is-disabled .el-select .el-input__inner {
  /* 在这里添加特定于el-select的样式 */
}
</style>
